package com.sparrow.common.thread;

import com.sparrow.common.schedule.FixTimeScheduledThreadPoolExecutor;
import com.sparrow.common.thread.factory.SimpleThreadFactory;
import com.sparrow.common.timer.GameWheelTimer;
import io.netty.util.HashedWheelTimer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 线程池
 */
public class ThreadPool {

    private static Logger logger = LoggerFactory.getLogger(ThreadPool.class);

    private static final int THREAD_COUNT = Runtime.getRuntime().availableProcessors() * 2;
    /**
     * 场景线程池
     */
    public static ExecutorService SCENE_EXECUTOR = Executors.newFixedThreadPool(THREAD_COUNT, new SimpleThreadFactory("Scene"));
    /**
     * 游戏循环线程
     */
    public static ExecutorService TICKER_EXECUTOR = Executors.newSingleThreadExecutor(new SimpleThreadFactory("Ticker"));
    /**
     * 共享的timer
     */
    public static GameWheelTimer TIMER = new GameWheelTimer(new SimpleThreadFactory("GameWheelTimer"), 100, TimeUnit.MILLISECONDS);
    /**
     * 可修正延迟时间的调度器
     */
    public static ScheduledExecutorService SCHEDULER = new FixTimeScheduledThreadPoolExecutor(20, new SimpleThreadFactory("Common-Scheduler"));

    public static void shutdown() {
        logger.info("公共ThreadPool 关闭进入");
        try {
            TICKER_EXECUTOR.shutdown();
            ThreadPool.TICKER_EXECUTOR.awaitTermination(20, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        try {
            ThreadPool.SCENE_EXECUTOR.shutdown();
            ThreadPool.SCENE_EXECUTOR.awaitTermination(20, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        try {
            ThreadPool.TIMER.stop();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try {
            ThreadPool.SCHEDULER.shutdown();
            ThreadPool.SCHEDULER.awaitTermination(20, TimeUnit.MINUTES);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        logger.info("公共ThreadPool 关闭结束");
    }
}
